package xyz.ag.Servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import xyz.ag.Beans.User;
import xyz.ag.Service.UserServiceInterface;
import xyz.ag.Service.impl.UserServiceInterfaceImpl;

/**
 * 用户接口,处理用户的相关信息
 * @author User
 *
 */
@WebServlet("*.douser")
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	/*变量*/
	UserServiceInterface userSI = new UserServiceInterfaceImpl();
	/*定义完成*/
   
    /**
     * 覆盖service方法 来实现对前端数据的接受
     */
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String method0  = req.getServletPath();//获取路径
		String method = "";
		try {//路径处理
			 method = method0.substring(1,method0.length()-7);
		} catch (Exception  a) {
			 method = method0.substring(1,method0.length()-7);
		}
		if("userload".equals(method)) UserLoad(req,resp);//跳转用户登录方法
		if("userloadcode".equals(method)) vcode(req,resp);//获得验证码的方法
		if("registered".equals(method)) registered(req,resp);//用户注册 
		if("userExit".equals(method)) userExit(req,resp);//用户退出
	}

	/**
	 * 用户退出方法
	 * 清除request域 清除session 清除COOKIE
	 * 这个方法暂时没有返回值
	 * 2019年12月7日18:13:30
	 * @param req
	 * @param resp
	 */
	private void userExit(HttpServletRequest req, HttpServletResponse resp) {
		User sessionuser = (User)req.getSession().getAttribute("user");
		Cookie cookie = new Cookie("mufengbook"+sessionuser.getUserName(),"");//设置Cookie 清除密码
		cookie.setMaxAge(1);//失效
		resp.addCookie(cookie);//设置Cookie
		req.getSession().setAttribute("user", null);//置空域对象
		try {
			resp.getWriter().write("{\"success\":\"1\"}");//通知前端  刷新页面
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}//通知前端刷新
	}


	/**
	 * 用户注册方法 传递的参数是4个值 包括用户名 密码 电话 ,地址
	 * 用户库进行入库 密码值进行MD5加密入库  这里封装一个用户对象
	 * ajax的支持方法 进行ajax的支持 这里返回json
	 *  success 用户状态 (+/-) id 成功之后的用户id
	 * @param req
	 * @param resp
	 */
	private void registered(HttpServletRequest req, HttpServletResponse resp) {
		resp.setContentType("json/text");
	    String username =  req.getParameter("username");
	    String password = req.getParameter("password");
	    String phonenumber = req.getParameter("phonenumber");
	    String address = req.getParameter("address");
		User nuser = new User.Builder().userName(username).userPassword(password).userPhoneNumber(phonenumber)
				.userAddress(address).build();
		Integer userid = userSI.createNewUser(nuser);
		String sreturn = "";
		if(userid!=0){
			sreturn = "{\"success\":\"1\",\"id\":\""+userid+"\"}";
		}else {
			sreturn = "{\"success\":\"-1\"}";
		}
		try {
			resp.getWriter().write(sreturn);
		} catch (IOException e) {
			System.err.println("注册返回时出错");
			e.printStackTrace();
		}
	}


	/**
	 * 这个方法用来输出验证码对象
	 * @param req 输入的request对象
	 * @param resp 输入的response对象
	 * 生成时间:2019年12月6日19:54:04
	 */
	private void vcode(HttpServletRequest req, HttpServletResponse resp) {
		resp.setContentType("image/jpeg");//设置返回值的类型
		Integer wX = 95;
		Integer wY = 38;
        String vCode = "";
        BufferedImage bufferedImage = new BufferedImage(wX,wY,BufferedImage.TYPE_3BYTE_BGR);
        Graphics graphics = bufferedImage.getGraphics();//由这个对象绘制图像
        char c[] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x'
                ,'y','z','A','B','C','D','E','F','G','H', 'I','J','K','L','M','N','O','P','Q','R','S','T','U','V',
                'W','X','Y','Z','1','2','3','4','5','6','7','8','9'};
        graphics.setColor(Color.white);
        graphics.fillRect(0, 0, 95, 38);
        graphics.setColor(Color.BLACK);
        for (int i=0;i<4;i++){
            Font font = new Font("黑体-繁",Font.BOLD,16+(int)new Random().nextDouble()*13);
            graphics.setFont(font);
            int a = (int)(new Random().nextDouble()*c.length);
            char cp = c[a];
            vCode = vCode+String.valueOf(cp);
            graphics.drawString(String.valueOf(cp),7+(i*20),32);
        }
        graphics.setColor(Color.BLACK);
        for (int i = 0; i < 20; i++) {
            int x = new Random().nextInt(95);
            int y = new Random().nextInt(38);
            int xl = new Random().nextInt(12);
            int yl = new Random().nextInt(12);
            graphics.drawLine(x, y, x + xl, y + yl);
            }
        req.getSession().setAttribute("vcode", vCode);//放到session域中去
        try {
			ImageIO.write(bufferedImage ,"jpg",resp.getOutputStream());
			//输出
		} catch (IOException e) {
			
			System.err.println("UserServlet92行验证码生成方法异常");
			e.printStackTrace();
		}
	}

	/**
	 * 用户登录方法
	 * 生成时间:2019年12月5日21:08:46
	 * 修改时间:2019年12月6日19:54:29
	 * 删除了增加Cooke密码的混淆 2019年12月8日10:04:46
	 * @param req
	 * @param resp
	 */
	private void UserLoad(HttpServletRequest req, HttpServletResponse resp) {
		resp.setContentType("json/text");
		String returns = "";//定义输出参量
		String remberme = req.getParameter("remberme");
		String userVCode = req.getParameter("userVCode");
		if(userVCode==null||!req.getSession().getAttribute("vcode").equals(userVCode)){//判断验证码是否正确 
			returns = "{\"success\":"+"0"+"}";//不正确则直接返回并有前端提示
			try {
				resp.getWriter().write(returns);
			} catch (IOException e) {
				System.err.println("登录输出异常");
				e.printStackTrace();
			};
			
			return;
		}
		
		String name = req.getParameter("username");
		String password = req.getParameter("password");
		
		User user = new User.Builder().userName(name).userPassword(password).build();//封装建议对象
		System.out.println("userCode="+userVCode+"remberme="+remberme);
		if(!"".equals(name)&&userSI.UserLogin(user)){//登陆成功
			if("true".equals(remberme)){
				Cookie cookie = new Cookie("mufengbook"+name,password/*+"|"+new Random().nextInt()*/);//设置Cookie 预备单次登录
				cookie.setMaxAge(900);//15分钟登录失效
				resp.addCookie(cookie);//设置Cookie
			}
			req.getSession().setAttribute("user", user);//设置用户对象
			returns = "{\"success\":"+"1"+",\"unamereturn\":\""+user.getUserName()+"\"}";
		}else{
			//登录失败
			returns = "{\"success\":"+"-1"+",\"url1\":\""+"2333"+"\"}";
		}
		//System.out.println(returns);
		try {
			resp.getWriter().write(returns);
		} catch (IOException e) {
			System.err.println("登录输出异常");
			e.printStackTrace();
		};
		
	}
    
    

	

}
